package com.artqiyi.dollmachine.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.artqiyi.dollmachine.R;
import com.artqiyi.dollmachine.common.Base.BaseApp;
import com.artqiyi.dollmachine.common.constant.ServerConstant;
import com.artqiyi.dollmachine.common.constant.UserConfigConstant;
import com.artqiyi.dollmachine.utils.AppUtils;
import com.artqiyi.dollmachine.utils.Callback.MyStringCallback;
import com.artqiyi.dollmachine.utils.JSONUtils;
import com.artqiyi.dollmachine.utils.manager.ConfigManager;
import com.artqiyi.dollmachine.utils.manager.HttpManager;
import com.artqiyi.dollmachine.utils.manager.UserInfoManager;
import com.artqiyi.dollmachine.utils.respone.ConfigRespone;
import com.artqiyi.dollmachine.utils.respone.UserInfoRespone;
import com.artqiyi.dollmachine.views.activity.LoginActivity;
import com.artqiyi.dollmachine.views.activity.MainActivity;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import timber.log.Timber;


public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

    private final String TAG = WXEntryActivity.class.getSimpleName();
    private static final int RETURN_MSG_TYPE_LOGIN = 1;
    private static final int RETURN_MSG_TYPE_SHARE = 2;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_loading);
        BaseApp.mWxApi.handleIntent(getIntent(), this);
    }

    // 微信发送请求到第三方应用时，会回调到该方法
    @Override
    public void onReq(BaseReq baseReq) {

    }

    // 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
    //app发送消息给微信，处理返回消息的回调
    @Override
    public void onResp(BaseResp resp) {

        switch (resp.errCode) {

            case BaseResp.ErrCode.ERR_AUTH_DENIED:
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                startActivity(new Intent(WXEntryActivity.this, LoginActivity.class));
                finish();
                break;
            case BaseResp.ErrCode.ERR_OK:
                switch (resp.getType()) {
                    case RETURN_MSG_TYPE_LOGIN:
                        //拿到了微信返回的code,立马再去请求access_token
                        String code = ((SendAuth.Resp) resp).code;
                        Log.d(TAG, "code=" + code);
                        //就在这个地方，用网络库什么的或者自己封的网络api，发请求去咯，注意是get请求
                        getUserInfo(code);
                        break;

                    case RETURN_MSG_TYPE_SHARE:
                        //分享成功后操作
                        finish();
                        break;
                }
                break;
        }
    }

    private void getUserInfo(String code) {
        Map<String, String> params = new HashMap<>();
        params.put("code", code);
        HttpManager.postHttpRequest(ServerConstant.wxLogin(), params, new MyStringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Timber.d("getUserInfo:" + e.getMessage());
                Toast.makeText(WXEntryActivity.this, "请求个人信息失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                Timber.d("个人信息：" + response);
                UserInfoRespone userInfoRespone = JSONUtils.jsonString2Bean(response, UserInfoRespone.class);
                if (userInfoRespone != null && userInfoRespone.getData() != null) {
                    Timber.d("Api_token:" + userInfoRespone.getData().getApi_token());
                    UserConfigConstant.setToken(userInfoRespone.getData().getApi_token());
                    UserInfoManager.getInstance().setUserInfoBean(userInfoRespone.getData());
                    getConfig();
                }
            }
        });
    }

    public void getConfig() {
        HttpManager.getHttpRequest(ServerConstant.getConfig(), null, new MyStringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Toast.makeText(WXEntryActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                Timber.d("response:" + response);
                ConfigRespone configRespone = JSONUtils.jsonString2Bean(response, ConfigRespone.class);
                if (null != configRespone && null != configRespone.getData()) {
                    ConfigManager.getInstance().setConfigBean(configRespone.getData());
//                    ConfigManager.getInstance().setFakePay(configRespone.getData().getFake_pay());
//                    ConfigManager.getInstance().setMallUrl(configRespone.getData().getMall_url());
//                    ConfigManager.getInstance().setSocketServerHost(configRespone.getData().getSocket_server_host());
                    ConfigManager.getInstance().setClosePay(TextUtils.equals(AppUtils.getVersionName(WXEntryActivity.this), configRespone.getData().getAuditing_version()));
//                    ConfigManager.getInstance().setApp_name(configRespone.getData().getApp_name());
                    startActivity(new Intent(WXEntryActivity.this, MainActivity.class));
                    finish();
                }
            }
        });
    }

}